package br.ucb.sigplan.action.impl;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.ucb.sigplan.action.Action;
import br.ucb.sigplan.beans.Cronograma;
import br.ucb.sigplan.beans.PlanoEnsino;
import br.ucb.sigplan.beans.Turma;
import br.ucb.sigplan.crud.CronogramaCrud;
import br.ucb.sigplan.crud.PlanoEnsinoCrud;
import br.ucb.sigplan.exception.DAOException;
import br.ucb.sigplan.util.CronogramaUtil;
import br.ucb.sigplan.validator.Validator;

public class AlteraCronogramaAction implements Action {

	@Override
	public String execute(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession();
		List<String> erros = Validator.validaCronogramaConcluido(req);
		if (!erros.isEmpty()) {
			req.setAttribute("erros", erros);
			return "/jsp/professor/cronograma/profAlteraCronograma.jsp";
		}
		PlanoEnsino planoEnsino = PlanoEnsinoCrud.findByTurma(new Turma((Integer) session.getAttribute("turma")));
		String msg = null;
		Cronograma cronograma = (Cronograma) session.getAttribute("cronograma");
		Cronograma cronogramaBanco = CronogramaCrud.searchByPlano(planoEnsino.getIdPlano());
		try {
			CronogramaUtil.adicionaConteudosAtividade(cronograma, cronogramaBanco, planoEnsino.getIdPlano());
			CronogramaUtil.deleteConteudosAtividade(cronograma, cronogramaBanco, planoEnsino.getIdPlano());
		} catch (DAOException e) {
			e.printStackTrace();
			msg = e.getMessage();
		}
		if (msg == null) {
			msg = "cronogramaAlteradoSucesso";
		}
		req.setAttribute("msg", msg);
		return "/jsp/index.jsp";
	}

}
